//
//  HomeController.swift
//  LiteAccount
//
//  Created by 刘伟 on 2017/5/4.
//  Copyright © 2017年 刘伟. All rights reserved.
//

// 主要逻辑： 展示上次数据库中存取的账本，展示添加账本逻辑


import UIKit

class HomeController: UIViewController, BaseViewProtocal {
    
    var data: AccountModel! {
        didSet {
            collectionView.reloadData()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setBaseViewConfig()
        prepareUI()
        layoutUI()
        initMJRefresh()
        loadData()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        MobClick.beginLogPageView("资产主页")
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        MobClick.endLogPageView("资产主页")
    }
    
    // 初始化下拉刷新
    func initMJRefresh() {
        let mjHeader = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(loadData))
        mjHeader?.lastUpdatedTimeLabel.font = UIFont.systemFont(ofSize: 12)
        mjHeader?.lastUpdatedTimeLabel.textColor = .black
        mjHeader?.stateLabel.font = UIFont.systemFont(ofSize: 15)
        mjHeader?.stateLabel.textColor = .black
        collectionView.mj_header = mjHeader
    }
    
    func loadData() {
        data = SQLiteClient.shared.fetchAccount()
        collectionView.mj_header.endRefreshing()
    }
    
    func saveAccount() {
        if checkLogin(target: self) { return }
        // 需要用户录入心情
        let inputView = InputController()
        inputView.titleText = "账本归档"
        inputView.detailText = "记录一下此刻的心情吧（选填）"
        // Create the dialog
        let popup = PopupDialog(viewController: inputView, buttonAlignment: .horizontal, transitionStyle: .bounceDown, gestureDismissal: true)
        
        // Create first button
        let buttonOne = CancelButton(title: "取消", height: 50) {
            debugPrint("取消归档")
        }
        
        let buttonTwo = DefaultButton(title: "确认归档", height: 50) {
            debugPrint("确认归档")
            ProgressHUD.show("正在归档账本，请稍候...", interaction: false)
            SQLiteClient.shared.getAccountDataForSave { (response) in
                switch response {
                case let .success(data as (String, String), _):
                    print(data.0, data.1)
                    var params = [String: Any]()
                    params["accountJson"] = data.0
                    params["detailJson"] = data.1
                    params["note"] = inputView.content
                    params["token"] = Defaults[.token]
                    debugPrint(params)
                    APIClient.shared.requestSaveAccount(params: params, getResponse: { (response) in
                        switch response {
                        case let .success(_, message):
                            ProgressHUD.showSuccess(message)
                        default: break
                        }
                    })
                case let .failure(message):
                    ProgressHUD.showError(message)
                default: break
                }
            }
        }
        popup.addButtons([buttonOne, buttonTwo])
        self.present(popup, animated: true, completion: nil)
    }
    
    // MARK: 将最新归档数据同步到当前账户
    func downloadAccount() {
        if checkLogin(target: self.tabBarController) {
            return
        }
        let dialog = confirmDialog(title: "温馨提示", message: "你确定要将最新归档数据同步到当前账本吗？") {
            ProgressHUD.show("正在同步账本，请稍候...", interaction: false)
            var params = [String: Any]()
            params["token"] = Defaults[.token]
            APIClient.shared.fetchLastAccount(params: params, getResponse: { (response) in
                ProgressHUD.dismiss()
                switch response {
                case let .success(data as AccountModel, _):
                    SQLiteClient.shared.rewriteCurrentAccount(account: data, getResponse: { (response) in
                        switch response {
                        case .success(_, _):
                            ProgressHUD.showSuccess("同步成功！")
                            self.loadData()
                        default: break
                        }
                    })
                default: break
                }
            })
        }
        self.present(dialog, animated: true, completion: nil)
    }
    
    fileprivate func prepareUI() {
        edgesForExtendedLayout = .init(rawValue: 0)
        self.view.backgroundColor = .white
        let downImg = resizeImage(image: UIImage(named: "icon_download.png")!, toSize: CGSize(width: 24, height: 16)).imageWithColor(tintColor: .white)
        self.navigationItem.leftBarButtonItem = UIBarButtonItem.barButton("同 步", titleColor: .white, image: downImg, hightLightImage: downImg, target: self, action: #selector(downloadAccount), type: .left)
        let upImg = resizeImage(image: UIImage(named: "icon_upload.png")!, toSize: CGSize(width: 24, height: 16)).imageWithColor(tintColor: .white)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.barButton("归 档", titleColor: .white, image: upImg, hightLightImage: upImg, target: self, action: #selector(saveAccount), type: .right)
        self.view.addSubview(collectionView)
    }
    
    fileprivate func layoutUI() {
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        collectionView.register(BookAccountCell.self, forCellWithReuseIdentifier: "Cell")
        collectionView.register(HomeHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerView")
    }
    
    // collectionView 的布局
    var layout: UICollectionViewFlowLayout {
        let object = UICollectionViewFlowLayout()
        // 设置 滑动方向
        object.scrollDirection = .vertical
        // 设置 每个 item 的大小
        object.itemSize = CGSize(width: (SCREEN_WIDTH - 15) / 2, height: 100)
        // 设置 每个 section 上下左右的间距
        object.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
        // 设置 行内 item 的最小间隔
        object.minimumInteritemSpacing = 5
        // 设置 每行 cell 之间的最小距离
        object.minimumLineSpacing = 5;
        // 设置 section 头部尺寸
        object.headerReferenceSize = CGSize(width: SCREEN_WIDTH, height: 120)
        return object
    }
    
    lazy var collectionView: UICollectionView = {
        let object = UICollectionView(frame: CGRect.zero, collectionViewLayout: self.layout)
        object.backgroundColor = UIColor.white
        object.bounces = true
        object.bouncesZoom = true
        object.delaysContentTouches = true
        object.contentMode = .scaleToFill
        object.dataSource = self
        object.delegate = self
        return object
    }()

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

extension HomeController: UICollectionViewDelegate, UICollectionViewDataSource {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headerView", for: indexPath) as! HomeHeaderView
        headerView.data = self.data
        return headerView
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data.detail.count + 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! BookAccountCell
        if indexPath.row == self.data.detail.count {
            cell.type = .add
        } else {
            cell.type = .edit
            cell.data = self.data.detail[indexPath.row]
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as! BookAccountCell
        let nextView = DetailController()
        var actionText = "添加"
        switch cell.type {
        case .edit:
            actionText = "编辑"
            nextView.data = self.data.detail[indexPath.row]
        default: break
        }
        // Create the dialog
        let popup = PopupDialog(viewController: nextView, buttonAlignment: .vertical, transitionStyle: .bounceDown, gestureDismissal: true)
        
        // Create first button
        let buttonOne = CancelButton(title: "取消", height: 40) {
            debugPrint("取消")
        }
        let buttonTwo = DefaultButton(title: actionText, height: 40) {
            debugPrint("确定")
            let name = nextView.name
            let amount = nextView.amount
            if name == "" {
                ProgressHUD.showError("亲，资产名称是必须项")
                shakeView(target: nextView.contentView)
                return
            }
            if amount == nil {
                ProgressHUD.showError("亲，资产金额录入有误")
                shakeView(target: nextView.contentView)
                return
            }
            switch cell.type {
            case .add:
                SQLiteClient.shared.addAccountDetailBy(name: name, amount: amount!, getResponse: { (response) in
                    switch response {
                    case let .success(_, message):
                        ProgressHUD.showSuccess(message)
                        self.loadData()
                    case let .failure(message):
                        ProgressHUD.showSuccess(message)
                    default: break
                    }
                })
                break
            case .edit:
                SQLiteClient.shared.updateAccountDetailBy(name: name, amount: amount!, getResponse: { (response) in
                    switch response {
                    case let .success(_, message):
                        ProgressHUD.showSuccess(message)
                        self.loadData()
                    case let .failure(message):
                        ProgressHUD.showSuccess(message)
                    default: break
                    }
                })
            }
            debugPrint(name, amount!)
            popup.dismiss()
        }
        let buttonThree = DefaultButton(title: "删除", height: 40) {
            let name = nextView.name
            SQLiteClient.shared.deleteAccountDetailBy(name: name, getResponse: { (response) in
                switch response {
                case let .success(_, message):
                    ProgressHUD.showSuccess(message)
                    self.loadData()
                case let .failure(message):
                    ProgressHUD.showSuccess(message)
                default: break
                }
            })
        }
        buttonTwo.dismissOnTap = false
        switch cell.type {
        case .add:
            popup.addButtons([buttonOne, buttonTwo])
        case .edit:
            buttonThree.setTitleColor(.red, for: .normal)
            popup.addButtons([buttonOne, buttonTwo, buttonThree])
        }
        present(popup, animated: true, completion: nil)
    }
}
